package dao;

import db.DbUtil;
import entity.Address;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author 蒋银辉
 * @version 1.0
 */
public class AddressDao {

    public int addToAddress(Address add) {
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String createTime = currentTime.format(formatter);
        int ret = DbUtil.getInstance().execute("insert into address_info(province,city,county,detail_address,address,recipient_name,recipient_phone,user_id,default_address,create_time,update_time) values(?,?,?,?,?,?,?,?,?,?,?)", new Object[]{add.getProvince(),add.getCity(),add.getCounty(),add.getDetailAddress(),add.getAddress(),add.getRecipientName(),add.getRecipientPhone(),add.getUserId(),0,createTime,createTime});
        return ret;
    }

    public int updateToAddress(Address add) {
        LocalDateTime currentTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String updateTime = currentTime.format(formatter);
        int ret = DbUtil.getInstance().execute("update address_info set province=?,city=?,county=?,detail_address=?,address=?,recipient_name=?,recipient_phone=?,default_address=?,update_time=? where address_id=?", new Object[]{add.getProvince(),add.getCity(),add.getCounty(),add.getDetailAddress(),add.getAddress(),add.getRecipientName(),add.getRecipientPhone(),add.getDefaultAddress(),updateTime,add.getAddressId()});
        return ret;
    }

    public List<Address> selectMyAddress(Integer userId) {
        List<Address> list=DbUtil.getInstance().queryList("select * from address_info where user_id=?",new Object[]{userId},Address.class);
        return list;
    }

    public int deleteToAddress(Integer addressId) {
        int ret = DbUtil.getInstance().execute("delete from address_info where address_id=?", new Object[]{addressId});
        return ret;
    }


    private Connection getConnection() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/shopping?useUnicode=true&characterEncoding=utf8",
                    "root", "123456");
            return conn;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    private void closeConnection(Statement stmt, Connection conn) {
        try {
            if (stmt != null) stmt.close();
            if (conn != null) conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


}